/*
 * @Author: HotSuitor
 * @Date: 2020-01-03 14:49:33
 * @LastEditors  : hs
 * @LastEditTime : 2020-01-09 09:47:36
 * @Description: 公共请求参数，非必要传参不要写在此文件，公共函数写到utils目录下
 */
import axios from 'axios'
import request from './axios'
import {
  appDevices,
  __VERSION__,
  nowTimeStamp,
  MD5Key,
} from '@/utils/loginEncrypt'
const storage = require('store')

function getSignRequest(data = {}) {
  return request
    .get(
      `api/agent/getSign?text=${'' +
        appDevices.deviceId +
        appDevices.clientId +
        __VERSION__ +
        nowTimeStamp +
        data.username +
        MD5Key(data.password)}`
    )
    .then(res => {
      return Promise.resolve(res.data)
    })
}

function isOwnEmptyObject(data) {
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      return false
    }
  }
  return true
}

let headers = {
  GL_DEVICE_ID: appDevices.deviceId,
  GL_CLIENT_ID: appDevices.clientId,
  GL_CLIENT_VER: __VERSION__,
  GL_CLIENT_APP_VER: appDevices.deviceAppVersion,
  GL_TIMESTAMP: nowTimeStamp,
}

async function login(data) {
  let sign = await getSignRequest(data)
  const instance = axios.create({
    baseURL: request.baseURL,
    timeout: process.env.VUE_APP_API_DEVELOPMENT,
    headers: Object.assign({}, headers, { GL_REQ_SIGN: sign }),
  })
  return instance
    .post('api/agent/login', {
      deviceName: 'iphone6',
      deviceVersion: '6.2.0',
      username: data.username,
      password: MD5Key(data.password),
      apiVersion: '0.0.1',
    })
    .then(res => Promise.resolve(res.data))
}

async function bsRequest() {
  let sign = await getSignRequest()
  const userInfo = storage.get('userInfo')
  if (isOwnEmptyObject(userInfo)) {
    return Promise.reject({ code: '1', msg: '请先登录' })
  }
  let token = userInfo.token

  const instance = axios.create({
    baseURL: request.baseURL,
    timeout: process.env.VUE_APP_API_DEVELOPMENT,
    headers: Object.assign({}, headers, { GL_TOKEN: token, GL_REQ_SIGN: sign }),
  })
  return instance
}

export default { bsRequest, login }
